package com.cloud.cloudshop.shop.controller.redis;

import com.cloud.cloudshop.config.redisson.RedisLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/redisson")
@Slf4j
public class RedissonTest {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/getLock")
    public void getLoct(){
        RLock test = redissonClient.getLock("test");

        System.out.println(test.getName());
        RLock test2 = redissonClient.getLock("test");
        System.out.println(test2.getName());


    }

    @GetMapping("/test")
    public void test() throws Exception {
        /**
         * 第一种
         */
        RedisLockUtil.lock("myLock");

        Thread.sleep(30000);
        log.info("耗子尾汁redis");

    }

    @GetMapping("/write")
    public void write() throws Exception {
        /**
         * 第一种
         */
        RLock myLock = RedisLockUtil.writeLock("RwLock");

        Thread.sleep(20000);


        RedisLockUtil.unlock(myLock);
        log.info("耗子尾汁redis");

    }

    @GetMapping("/read")
    public void read() throws Exception {
        /**
         * 第一种
         */
        RLock myLock = RedisLockUtil.readLock("RwLock");
        log.info("拿到锁了");
        Thread.sleep(15000);
        RedisLockUtil.unlock(myLock);
        log.info("耗子尾汁redis");

    }

    @GetMapping("/read2")
    public void read2() throws Exception {
        /**
         * 第一种
         */
        RLock myLock = RedisLockUtil.readLock("RwLock");
        log.info("拿到锁了2");
        Thread.sleep(15000);
        RedisLockUtil.unlock(myLock);
        log.info("耗子尾汁redis222");

    }
}

